<?php
use think\Cache;
use think\Log;
class WeChat {
    /**
     * 生成随机字符串
     */
    public static function make_nonceStr() {
        $codeSet = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for ($i = 0; $i < 16; $i++) {
            $codes[$i] = $codeSet[mt_rand(0, strlen($codeSet) - 1)];
        }
        $nonceStr = implode($codes);
        return $nonceStr;
    }
    /**
     * 生成签名字符串
     */
    public static function make_signature($jsapi_ticket,$noncestr,$url,$timer) {
        $tmpArr = array(
            'noncestr' => $noncestr,
            'jsapi_ticket' => $jsapi_ticket,
            'timestamp' => $timer,
            'url' => $url
        );
        ksort($tmpArr, SORT_STRING);
        $string1 = http_build_query($tmpArr);
        $string1 = urldecode($string1);
        $signature = sha1($string1);
        return $signature;
    }
    /**
     * 获取ticket
     *
     * @param [type] $appid
     * @param [type] $secret
     * @return bool|string  返回false 或access_token
     */
    public static function getWxAccessToken($appid,$secret) {
        //  Cache::set('access_token_wxae6063aff3a7ee71', $list['91_OD0Yfbu3-y_EWkAL_5UqizrE3TA0HaAHLfFywgge5v2xvqSMu-Hj_6hsqaJQa1dalPEcV9jVSsJo8nhSps78YxgnQcUHxkMc9PPZ1tUcMUvdWC2BHX5aLkaPBZ8VXBhACAGIM'], 7200);
        if (Cache::has('access_token_'.$appid)) {
            return Cache::get('access_token_'.$appid);
        }
        $get = array(
            'appid'     => $appid,
            'secret'    => $secret,
            'grant_type'=> 'client_credential'
        );
        $res = self::curlGet('https://api.weixin.qq.com/cgi-bin/token', $get);
        //Log::error('getWxAccessToken:'.$res);
        $list = json_decode($res, true);

        if ($list['access_token']) {
            Cache::set('access_token_'.$appid, $list['access_token'], 7200);
            return $list['access_token'];
        } else {
            return false;
        }
    }
    /**
     * 获取ticket
     *
     * @param [type] $appid
     * @param [type] $secret
     * @return bool|string  返回false 或ticket
     */
    public static function getWxTicket($appid,$secret) {
        $ticket = Cache::get('ticket_'.$appid,'');
        if ($ticket) {
            return $ticket;
        }
        $access_token = self::getWxAccessToken($appid,$secret);
        $get =  [
            'access_token' => $access_token,
            'type' => 'jsapi'
        ];
        $ticket_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
        $res  = self::curlGet($ticket_URL, $get);
        $list = json_decode($res, true);
        if ($list['errcode'] == 0) {
            Cache::set('ticket_'.$appid, $list['ticket'], 7200);
            return $list['ticket'];
        } else {
            return false;
        }
    }
    /**
     * 物流查询插件获取waybillToken
     *
     * @param string $appid
     * @param string $secret
     * @param array $data
     * @return bool|string  返回''或waybill_token
     */
    public static function getWaybillToken($appid,$secret,$data)
    {
        try{
            $access_token = self::getWxAccessToken($appid,$secret);
            Log::error($access_token);
            $result = self::curlPost('https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/follow_waybill?access_token='.$access_token,$data);
            Log::error('getWaybillToken:'.$result);
            $result = json_decode($result,true);
            if($result['errcode'] === 0){
                return $result['waybill_token'];
            }
        }catch(Exception $e){
            Log::error($e->getMessage());
            return '';
        }   
        return '';          
    }
    /**
     * 生成小程序链接
     *
     * @param string $appid 小程序APPID
     * @param string $secret 小程序密钥
     * @param string $path   访问的链接
     * @param array $query  附带的参数
     * @return bool|string  返回false 或url_link
     */
    public static function create_urlink($appid,$secret,$path='pages/index',$query=[]){
        try{
            $access_token = self::getWxAccessToken($appid,$secret);
            $data['query'] = !empty($query)?http_build_query($query):'';
            $data['path']  = $path;
            $data['expire_type'] = 0;
            $data['expire_time'] = time() + 3*86400;
            $result = self::curlPost('https://api.weixin.qq.com/wxa/generate_urllink?access_token='.$access_token,json_encode($data));
            Log::error($result);
            $result = json_decode($result,true);
            if($result['errcode'] === 0){
                return $result['url_link'];
            }
        }catch(Exception $e){
            Log::error($e->getMessage());
        }   
        return false;      
    }
    /**
     * 小程序用户解密手机号
     */
    public static function get_phoneNum($appid,$secret,$data)
    {
        try{
            if(!empty($data['code'])){
               
                $token = self::getWxAccessToken($appid,$secret);
                $post  = [
                    'code'=> $data['code']
                ];
                $result = curlPost('https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$token, json_encode($post));  
                $result = json_decode($result,true);
                return $result;
            }
            
        }catch (\Exception $e){
            Log::error('获取手机号错误:'.$e->getMessage().json_encode($data).json_encode($result));
            return ['errcode'=>1,'msg'=>'参数错误','data'=>[]];
        }    
    }
    /**
     * 使用curl发送GET请求
     * @param  string $url 需要发送的URL地址
     * @param  array  $get 需要发送的数据
     * @param  int    $timeout 尝试连接等待的时间，单位：秒，默认5分钟
     * @return bool|string 出错返回FALSE, 否则返回网页内容
     */
    static function curlGet($url, $get = null, $agent = '', $timeout = 300, $charset='') {
        if (!is_string($get)) $get = http_build_query($get);     //生成 URL-encode 之后的请求字符串
        if ($get) $url .= '?' . $get;
        $ch = curl_init();                                  //初始化一个CURL会话

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_USERAGENT, $agent);
        //curl_setopt($ch, CURLOPT_POST, false);            //启用时会发送一个常规的POST请求
        curl_setopt($ch, CURLOPT_HEADER, false);            //启用时会将头文件的信息作为数据流输出。
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    //禁用后cURL将终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);        //检查服务器SSL证书中是否存在一个公用名
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;    //获取数据返回
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;    //在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //尝试连接等待的时间，单位：秒，默认5分钟
        if ($charset) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml; charset=' . $charset));
        }

        $return = curl_exec($ch);
        curl_close($ch);

        return $return;
    }
    
    static function curlPost($url, $post, $agent = '', $timeout = 300, $header = '') {
        if (!is_string($post)) $post = http_build_query($post);             //生成 URL-encode 之后的请求字符串
        $ch = curl_init();                                  //初始化一个CURL会话
        curl_setopt($ch, CURLOPT_URL, $url);                //需要发送的URL地址
        curl_setopt($ch, CURLOPT_USERAGENT, $agent);
        curl_setopt($ch, CURLOPT_POST, true);               //启用时会发送一个常规的POST请求
        curl_setopt($ch, CURLOPT_HEADER, false);            //启用时会将头文件的信息作为数据流输出。
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    //禁用后cURL将终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);        //检查服务器SSL证书中是否存在一个公用名
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;    //获取数据返回
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     //启用CURLOPT_RETURNTRANSFER的时候，返回原生的（Raw）输出
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //需要发送的数据
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //尝试连接等待的时间，单位：秒，默认5分钟
        if($header){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        $return = curl_exec($ch);
        curl_close ($ch);

        return $return;
    }
    /**
     * 数据请求
     * @param $url
     * @param array $header 获取头部
     * @param string $post_data POST数据，不填写默认以GET方式请求
     * @return bool|string
     */
    private static function http_Request($url, $header = array(), $post_data = "")
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 2);
        curl_setopt($ch, CURLOPT_HEADER,0);
        if ($post_data != "") {
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); //设置post提交数据
        }
        //判断当前是不是有post数据的发
        $output = curl_exec($ch);
        if ($output === FALSE) {
            $output = "curl 错误信息: " . curl_error($ch);
        }
        //Log::error(curl_getinfo($ch));
        curl_close($ch);
        //Log::error(json_encode($output));
        return $output;

    }

    /**
     *  生成小程序码
     *
     * @param string $appid
     * @param string $secret
     * @param string $path
     * @param array $query
     * @param string $openid
     * @return string
     */
    public static function create_wxaqrcode($appid,$secret,$path,$query=[],$openid=''){
        try{
            $access_token  = self::getWxAccessToken($appid,$secret);
            if(!$access_token)return json_encode(['code'=>1,'data'=>'','msg'=>'access_token无效']);
            $data['path']  = $path;
            if(!empty($query)){
                $data['path'] .= '?'.http_build_query($query);
                //Log::error($data['path']);
            }
            $result = self::curlPost('https://api.weixin.qq.com/wxa/getwxacode?access_token='.$access_token,json_encode($data));
            $base64_image ="data:image/jpeg;base64,". base64_encode($result);
            return self::base64EncodeImage($base64_image,$path,$openid);
        }catch(Exception $e){
            Log::error($e->getMessage());
            //return false;
        }    
        return json_encode(['code'=>1,'data'=>'']);    
    }
    /**
    * 保存二维码图片
    *
    * @param string $base64_image_content
    * @param string $path
    * @param string $openid
    * @return string 
    */
    public static function  base64EncodeImage ($base64_image_content,$path='',$openid='') {
        //匹配出图片的格式
        //Log::error($base64_image_content);
        try{
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
                $type = $result[2];
                if($path == ''){
                    $path_arr = date('Y-m-d');
                }else{
                    $path_arr = $path;
                }
                $new_file  = ROOT_PATH."public/wx_code/images/".$path_arr.'/';
                if(!file_exists($new_file)){
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                    mkdir($new_file, 0777,true);
                }
                if($openid){
                    $name = $openid.'.'.$type;
                }else{
                    $name = time().'.'.$type;
                }
                $new_file = $new_file.$name;
                
                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                        return json_encode(['code'=>0,'data'=>['url'=>$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/wx_code/images/'.$path_arr.'/'.$name]]);
                    }
            }else{
                return json_encode(['code'=>1,'data'=>'','msg'=>'格式不匹配']);
            }
        }catch(Exception $e){
            Log::error('base64EncodeImage:'.$e->getMessage());
            return json_encode(['code'=>1,'data'=>'']);
        }   
        
    }
    public static function follow_waybill($appid,$secret,$data){
        try{
            $waybill_id   = Cache::get('Exp_'.$data['waybill_id'],'');
            if(!empty($waybill_id))return $waybill_id;
            $access_token = self::getWxAccessToken($appid,$secret);
            $result = self::curlPost('https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/follow_waybill?access_token='.$access_token,$data);
            Log::error('getWaybillToken:'.$result);
            $result = json_decode($result,true);
            if($result['errcode'] === 0){
                Cache::set('Exp_'.$data['waybill_id'],$result['waybill_token'],7200);
                return $result['waybill_token'];
            }
        }catch(Exception $e){
            Log::error($e->getMessage());
            return '';
        }   
        return '';    
    }
    /**
     * 获取订单物流状态
     *
     * @param [type] $appid
     * @param [type] $secret
     * @param array $data
     * @return void
     */
    public static function query_trace($appid,$secret,$data=[]){
        if(empty($data))return false;
        if (Cache::has('EXPRESS_'.$data['waybill_token'])) {
            return Cache::get('EXPRESS_'.$data['waybill_token']);
        }
        try{
            $access_token = self::getWxAccessToken($appid,$secret);
            $result = self::curlPost('https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/query_trace?access_token='.$access_token,$data);
            $result = json_decode($result,true);
            if($result['errcode'] === 0){
                Cache::set('EXPRESS_'.$data['waybill_token'],$result['waybill_info']['status'],3600);
                return $result['waybill_info']['status'];
            }
        }catch(Exception $e){
            Log::error($e->getMessage());
            return false;
        }   
    }
    /**
     * 获取公众号ticket
     *
     * @param [type] $appid
     * @param [type] $secret
     * @param [type] $number
     * @return bool|string
     */
    public static function getcodeticket($appid,$secret,$number){
        try{
            $access_token = self::getWxAccessToken($appid,$secret);
            $url  = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;
            $data = [
                'expire_seconds' => 2592000,
                'action_name' => 'QR_STR_SCENE',
                'action_info' => [
                    'scene' => [
                        'scene_str'=>(string)$number
                    ]
                ]
            ];
            $result = self::curlPost($url,json_encode($data));
            $res_data = json_decode($result,true);
            return $res_data['ticket'];
        }catch(Exception $e){
            Log::error('公众号获取ticket'.$e->getMessage());
            return false;
        }
    }
    /**
     * 获取公众号二维码
     *
     * @param [type] $appid
     * @param [type] $secret
     * @param [type] $number
     * @return string
     */
    public static function createCode($appid,$secret,$number=1){
        try{
            $ticket_data = Cache::get('ticket_data_'.$number,'');
            if($ticket_data == '')$ticket_data = self::getcodeticket($appid,$secret,$number);
            Cache::set('ticket_data_'.$number,$ticket_data,2592000);
            Log::error('ticket_data:'.$ticket_data);
            if(!$ticket_data)throw new Exception('获取ticket失败');
            return 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$ticket_data;
        }catch(Exception $e){
            throw new Exception($e->getMessage());
        }
    }
    /**
     * 订单发货同步
     *
     * @param [type] $appid
     * @param [type] $secret
     * @param [type] $order
     * @return void
     */
    public static function upload_shipping_info($appid,$secret,$order){
        try{
            $logistics_type = 1;
            $express_company = '';
            $express_no =  $order['express_no'];
            if (strpos($order['express_name'], '自提') !== false || empty($order['express_no'])) {
                $logistics_type = 4;
                $express_no = '';
            }else{
                $express_company = self::get_company_list($appid,$secret,$order['express_name']);
            }
            $access_token = self::getWxAccessToken($appid,$secret);
            $url  = 'https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token='.$access_token;
            $post = [
                'order_key' => [
                    'order_number_type' => 1,
                    'mchid'          => $order['sub_mchid'],
                    'transaction_id' => $order['transaction_id'],
                    'out_trade_no'   => $order['order_no']
                ],
                'logistics_type' => $logistics_type,
                'delivery_mode'  => 1,
                'shipping_list'  => [
                    [
                        'tracking_no' => $express_no,
                        'express_company' => $express_company,
                        'item_desc' => '随身WIFI设备',
                        'contact'   => [
                            'receiver_contact' => trim($order['tel'])
                        ]
                    ]
                ],
                'upload_time' => date('c'),
                'payer' => [
                    'openid' => $order['openid']
                ]
            ];
            //dump($post);exit();
            $result = self::curlPost($url,json_encode($post,JSON_UNESCAPED_UNICODE));
            Log::error('微信小程序订单发货同步:'.$result);
            $result = json_decode($result,true);
            if($result['errcode'] != 0)return false;
        }catch(Exception $e){
            Log::error('微信小程序订单发货同步：'.$e->getMessage());
            //throw new Exception($e->getMessage());
        }
        return true;
    }
    /**
     * 获取运力id
     *
     * @param [type] $appid
     * @param [type] $secret
     * @param [type] $express_name
     * @return void
     */
    public static function get_company_list($appid,$secret,$express_name){
        $arr = [
            '自提'=>'',
            '圆通'=>'YTO',
            '中通'=>'ZTO',
            '顺丰'=>'SF',
            '邮政'=>'EMS',
            '德邦'=>'DB',
            '申通'=>'STO',
            '京东'=>'JDL',
            '天天'=>'HHTT',
            '极兔'=>'JTSD',
            '韵达'=>'YUNDA',
            '百世'=>'BEST',
            '优速'=>'UCE',
        ];
        return $arr[mb_substr(trim($express_name),0,2)];
    }
    public static function get_delivery_list($appid,$secret){
        $access_token = self::getWxAccessToken($appid,$secret);
        $url    = 'https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/get_delivery_list?access_token='.$access_token;
        $result = json_decode(self::curlPost($url,'{}'),true);
        //dump($result);exit();
        $list   = $result['company_list'];
        return $list;
        
    }
    /**
     * 发送订阅消息
     *
     * @param string $appid
     * @param string $secret
     * @param string $openid
     * @param string $template_id
     * @param array $data
     * @param string $page
     * @return void
     */
    public static function subscribe_send($appid,$secret,$openid,$template_id,$data,$page=''){
        $url  = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.self::getWxAccessToken($appid,$secret);
        $post = [
            'template_id' => $template_id,
            'touser'      => $openid,
            'miniprogram_state' => 'formal',//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
            'data'        => $data, //模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }的object
            'lang'        => 'zh_CN',//进入小程序查看”的语言类型，支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为zh_CN
            'page'        => $page
        ];
        $result = self::curlPost($url,json_encode($post));
        $result = json_decode($result,true);
        return $result;
    }

    public static function msg_notify() {
        if (isset($_GET['echostr'])) {
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];
            $token = 'wkh';
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
    
            if ($tmpStr == $signature) {
                echo $_GET['echostr'];
                exit();
            } else {
                return false;
            }
        } else {
            $postArr = file_get_contents("php://input");
            //$postArr = file_get_contents("php://input");
            //2.处理消息类型，并设置回复类型和内容
            $postObj = simplexml_load_string( $postArr );
            Log::error('公众号'.$postObj->EventKey);
            //判断该数据包是否是订阅的事件推送
            if( strtolower( $postObj->MsgType) == 'event'){
                //如果是关注 subscribe 事件
                if( strtolower($postObj->Event) == 'subscribe' ){
                    self::getUserInfo($postObj->FromUserName, 'subscribe');
                    //回复用户消息(纯文本格式)
                    $toUser   = $postObj->FromUserName;
                    $fromUser = $postObj->ToUserName;
                    $time     = time();
                    $msgType  =  'text';
                    if ($postObj->EventKey == 'qrscene_9001') {
                        $content  = "终于等到您，还好没放弃！\r\n \r\n<a data-miniprogram-appid='wx95d8956a1cd87925' data-miniprogram-path='/pages/index/index?form_id=9999'>开启5折上网权益点击这里↙</a>\r\n\r\n";
                    } else {
                        $content  = '<a data-miniprogram-appid="wx95d8956a1cd87925" data-miniprogram-path="/pages/index/index" >感谢您的关注，请点击链接参加全民降费活动！</a>';
                    }
                    $template = "<xml><ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content></xml>";
                    $info     = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
                    echo $info;
                } elseif ($postObj->Event == 'unsubscribe') {
                    //取消
                    Log::info('取消事件：'.$postObj->FromUserName);
                    self::getUserInfo($postObj->FromUserName, 'unsubscribe');
                }
            }
        }
    }
    
    /**
     * 获取沃免费公众号关注用户的unionid
     * Date: 2019/11/27
     * @param $openid
     */
    private function getUserInfo($openid, $event) {
        if ($event == 'subscribe') {
            if (isset($list['unionid'])) {
                
            }
        } else {
            //取消事件
            Log::info('取消事件1：'.$openid);
        }
    }
    /**
     * 解析Unionid
     *
     * @param [type] $appid
     * @param [type] $secret
     * @param [type] $openid
     * @return void
     */
    public static function getMpUunionid($appid,$secret,$openid) {
        $access_token = self::getWxAccessToken($appid,$secret);
        $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
        $res  = self::curlGet($url,[]);
        $list = json_decode($res, true);
        return $list;
    }
     /**
     * 运费险发货时创建保单
     *
     * @param [type] $appid
     * @param [type] $secret
     * @param [array] $order
     * @return void
     */
    
    public static function create_policy($appid,$secret,$order){
        $access_token = self::getWxAccessToken($appid,$secret);
        $url  = 'https://api.weixin.qq.com/wxa/business/insurance_freight/createorder?access_token='.$access_token;
        $data = [
              "openid"=>$order['openid'],
              "order_no"=> $order['order_no'],
              "pay_amount"=>$order['order_amount']*100,
              "pay_time"=>strtotime($data['pay_time']),
              "delivery_place"=>[
                  "province"=>"广东省",
                  "city"=>"深圳市",
                  "county"=>"罗湖区",
                  "address"=>"宝安北路1007号笋岗仓库区 HALO广场三期5层509"
              ],
              "receipt_place"=>[
                  "province"=>$order[''],
                  "city"=> "惠州市",
                  "county"=> "惠普区",
                  "address"=> "龙山村10-2"
              ],
              "delivery_no"=>"d20230322001"
            ];
        $result = self::curlPost($url,json_encode($data,JSON_UNESCAPED_UNICODE));
        Log::error('运费险：'.$result);
        return json_encode($result,true);
    }/**
     * 理赔保单
     * @param [type] $appid
     * @param [type] $secret
     * @param [array] $data = {
            "openid": "oZGTP5DwGDPfEf1EBBHH_oxHw2aU",
            "order_no": "4200001197202103228672982585",
            "refund_delivery_no" : "rd20230322001",
            "refund_company": "SF"
        }
     * @return void
     */
    public static function claim($appid,$secret,$data){
        $access_token = self::getWxAccessToken($appid,$secret);
        $url = 'https://api.weixin.qq.com/wxa/business/insurance_freight/claim?access_token='.$access_token;
        $result = self::curlPost($url,json_encode($data,JSON_UNESCAPED_UNICODE));
        Log::error('理赔：'.$result);
        return json_encode($result,true);
    }
    public static function createMenu($appid,$secret){
        $access_token = self::getWxAccessToken($appid,$secret);
        $url  = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
        $menu = [
            'button' => [
                    [
                        'name' => '业务管理',
                        'type' => 'miniprogram',
                        'url'  => 'https://wkh.wokahui.cn/api/notify/error',
                        'appid'=> 'wxae6063aff3a7ee71',
                        'pagepath' =>'pages/auth/entrance/index?to=home'
                        ],
                    [
                        'name'=>'业务动态',
                        'type' => 'miniprogram',
                        'url'  => 'https://wkh.wokahui.cn/api/notify/error',
                        'appid'=> 'wxae6063aff3a7ee71',
                        'pagepath' =>'pages/auth/entrance/index?to=order'
                        ],
                    [
                        'name' =>'在线提货',
                        'type' => 'miniprogram',
                        'url'  => 'https://wkh.wokahui.cn/api/notify/error',
                        'appid'=> 'wxae6063aff3a7ee71',
                        'pagepath' =>'pages/auth/entrance/index?to=onlineOrdering'
                        ]
                ]
            ];
        $result = self::curlPost($url,json_encode($menu,JSON_UNESCAPED_UNICODE));
        return $result;
    }
    /**
     * 发送公众号模板
     *
     * @param string $appid 公众号 AppID
     * @param string $secret 公众号密钥
     * @param string $openid 接收消息用户的 OpenID
     * @param string $template_id 模板消息 ID
     * @param array $data 模板消息内容数据
     * @param string $miniprogram :{appid:'',pagepath:''}跳转的小程序页面路径
     * @return mixed 返回微信服务器响应结果
     */
    public static function sendTemplateMessage($appid, $secret, $openid, $template_id, $data, $miniprogram=null) {
        // 获取 access_token
        $access_token = self::getWxAccessToken($appid, $secret);        
        // 构造请求 URL
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";
        // 构造请求数据
        $postData = [
            'touser' => $openid,
            'template_id' => $template_id,
            'data' => $data
        ];
        // 如果设置了小程序页面路径
        if (!empty($miniprogram)) {
            $postData['miniprogram'] = $miniprogram;
        }
        // 发送 POST 请求
        $response = self::curlPost($url, json_encode($postData, JSON_UNESCAPED_UNICODE));
        // 解析返回结果
        return json_decode($response, true);
    }
}

